nomy-data-models 0.2.5

Data model definitions for Nomy wallet analysis data processing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
"""Tests for the Python to Rust conversion utility."""

import os
import sys
import tempfile
from enum import Enum
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Type, Union, cast
from unittest.mock import MagicMock, PropertyMock, mock_open, patch

import pytest
from sqlalchemy import (
    UUID,
    Boolean,
    Column,
    Date,
    DateTime,
)
from sqlalchemy import Enum as SQLAlchemyEnum
from sqlalchemy import (
    Float,
    Integer,
    Interval,
    Numeric,
    String,
    Time,
)
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Mapped, mapped_column

import nomy_data_models
from nomy_data_models.models.base import BaseModel
from nomy_data_models.py_to_rust import (
    _generate_rust_fields,
    _print_unknown_type_warning,
    generate_rust_enum,
    generate_rust_model,
    generate_rust_models,
    get_all_models,
    get_required_imports,
    sqlalchemy_to_rust_type,
)


class StatusEnum(str, Enum):
    """Test status enum for testing enum conversion."""

    ACTIVE = "active"
    INACTIVE = "inactive"
    PENDING = "pending"


class DirectionEnum(str, Enum):
    """Test direction enum for testing enum conversion."""

    UP = "up"
    DOWN = "down"
    SIDEWAYS = "sideways"


class RustModelExample(BaseModel):
    """Test model for testing model to Rust conversion."""

    __abstract__ = False

    name: Mapped[str] = mapped_column(String(50), nullable=False)
    age: Mapped[int] = mapped_column(Integer, nullable=False)
    is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
    created_at: Mapped[DateTime] = mapped_column(DateTime, nullable=False)
    model_id: Mapped[UUID] = mapped_column(UUID, nullable=False)
    data: Mapped[dict] = mapped_column(JSONB, nullable=True)
    amount: Mapped[float] = mapped_column(Float, nullable=True)
    decimal_value: Mapped[float] = mapped_column(Numeric, nullable=True)
    date_value: Mapped[Date] = mapped_column(Date, nullable=True)
    time_value: Mapped[Time] = mapped_column(Time, nullable=True)
    interval_value: Mapped[Interval] = mapped_column(Interval, nullable=True)


class AbstractModel(BaseModel):
    """Abstract model for testing abstract model handling."""

    __abstract__ = True


class ConcreteAbstractModel(AbstractModel):
    """Concrete model that inherits from an abstract model but has table attributes."""

    __abstract__ = False
    name: Mapped[str] = mapped_column(String(50), nullable=False)


class ModelWithTableArgs(BaseModel):
    """Model with __table_args__."""

    __abstract__ = False

    __table_args__ = {"sqlite_autoincrement": True}
    name: Mapped[str] = mapped_column(String(50), nullable=False)


@pytest.fixture
def test_status_enum():
    """Fixture providing the TestStatus enum."""
    return StatusEnum


@pytest.fixture
def test_direction_enum():
    """Fixture providing the TestDirection enum."""
    return DirectionEnum


@pytest.fixture
def test_rust_model():
    """Fixture providing a TestRustModel instance."""
    return RustModelExample


class TestRustEnumGeneration:
    """Test cases for Rust enum generation."""

    def test_generate_rust_enum(self, test_status_enum):
        """Test generating Rust enum from Python enum.

        Args:
            test_status_enum: Fixture providing the TestStatus enum
        """
        rust_enum = generate_rust_enum(test_status_enum)

        # Check that the enum is generated correctly
        assert (
            "#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]"
            in rust_enum
        ), "Rust enum should have the correct derive attributes"

        assert (
            "pub enum StatusEnum {" in rust_enum
        ), "Rust enum should have the correct name"

        # Check enum variants
        assert (
            '#[serde(rename = "active")]' in rust_enum
        ), "ACTIVE variant should have correct serde rename"
        assert "ACTIVE," in rust_enum, "ACTIVE variant should be present"
        assert (
            '#[serde(rename = "inactive")]' in rust_enum
        ), "INACTIVE variant should have correct serde rename"
        assert "INACTIVE," in rust_enum, "INACTIVE variant should be present"
        assert (
            '#[serde(rename = "pending")]' in rust_enum
        ), "PENDING variant should have correct serde rename"
        assert "PENDING," in rust_enum, "PENDING variant should be present"

        # Check that the impl block is generated
        assert "impl StatusEnum {" in rust_enum, "Rust enum should have an impl block"
        assert (
            "pub fn as_str(&self) -> &'static str {" in rust_enum
        ), "as_str method should be present"
        assert "match self {" in rust_enum, "match statement should be present"
        assert (
            'StatusEnum::ACTIVE => "active",' in rust_enum
        ), "ACTIVE match arm should be present"

    def test_generate_rust_enum_with_different_enum(self, test_direction_enum):
        """Test generating Rust enum from a different Python enum.

        Args:
            test_direction_enum: Fixture providing the TestDirection enum
        """
        rust_enum = generate_rust_enum(test_direction_enum)

        # Check that the enum is generated correctly
        assert (
            "#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]"
            in rust_enum
        ), "Rust enum should have the correct derive attributes"

        assert (
            "pub enum DirectionEnum {" in rust_enum
        ), "Rust enum should have the correct name"

        # Check enum variants
        assert (
            '#[serde(rename = "up")]' in rust_enum
        ), "UP variant should have correct serde rename"
        assert "UP," in rust_enum, "UP variant should be present"
        assert (
            '#[serde(rename = "down")]' in rust_enum
        ), "DOWN variant should have correct serde rename"
        assert "DOWN," in rust_enum, "DOWN variant should be present"
        assert (
            '#[serde(rename = "sideways")]' in rust_enum
        ), "SIDEWAYS variant should have correct serde rename"
        assert "SIDEWAYS," in rust_enum, "SIDEWAYS variant should be present"

        # Check that the impl block is generated
        assert (
            "impl DirectionEnum {" in rust_enum
        ), "Rust enum should have an impl block"
        assert (
            "pub fn as_str(&self) -> &'static str {" in rust_enum
        ), "as_str method should be present"
        assert "match self {" in rust_enum, "match statement should be present"
        assert (
            'DirectionEnum::UP => "up",' in rust_enum
        ), "UP match arm should be present"
        assert (
            'DirectionEnum::DOWN => "down",' in rust_enum
        ), "DOWN match arm should be present"
        assert (
            'DirectionEnum::SIDEWAYS => "sideways",' in rust_enum
        ), "SIDEWAYS match arm should be present"

    def test_generate_rust_enum_with_numeric_values(self):
        """Test generating Rust enum from a Python enum with numeric values."""

        class NumericEnum(Enum):
            ONE = 1
            TWO = 2
            THREE = 3

        rust_enum = generate_rust_enum(NumericEnum)

        # Check that the enum is generated correctly
        assert "pub enum NumericEnum {" in rust_enum
        assert "ONE = 1," in rust_enum
        assert "TWO = 2," in rust_enum
        assert "THREE = 3," in rust_enum
        assert 'numericenum::one => "one",' in rust_enum.lower()


class TestRustTypeConversion:
    """Test cases for SQLAlchemy to Rust type conversion."""

    @pytest.mark.parametrize(
        "sqlalchemy_type,expected_rust_type",
        [
            ("Integer", "i32"),
            ("BigInteger", "i64"),
            ("SmallInteger", "i16"),
            ("String", "String"),
            ("Text", "String"),
            ("Boolean", "bool"),
            ("Float", "f64"),
            ("Numeric", "Decimal"),
            ("DateTime", "DateTime<Utc>"),
            ("Date", "NaiveDate"),
            ("Time", "NaiveTime"),
            ("UUID", "Uuid"),
            ("JSON", "JsonValue"),
            ("JSONB", "JsonValue"),
            ("Interval", "chrono::Duration"),
            ("Enum", "String"),
            ("uuid", "Uuid"),  # Case insensitive for UUID
            ("UnknownType", "String"),  # Unknown type defaults to String
        ],
    )
    def test_sqlalchemy_to_rust_type(self, sqlalchemy_type, expected_rust_type):
        """Test converting SQLAlchemy types to Rust types.

        Args:
            sqlalchemy_type: SQLAlchemy type name
            expected_rust_type: Expected Rust type
        """
        # Test without column (for backward compatibility)
        result = sqlalchemy_to_rust_type(sqlalchemy_type)
        assert result == expected_rust_type

        # Test with non-nullable column
        mock_column = MagicMock()
        mock_column.nullable = False
        mock_column.type = MagicMock()
        mock_column.type.python_type = str
        result = sqlalchemy_to_rust_type(sqlalchemy_type, mock_column)
        assert result == expected_rust_type

        # Test with nullable column
        mock_column.nullable = True
        result = sqlalchemy_to_rust_type(sqlalchemy_type, mock_column)
        assert result == f"Option<{expected_rust_type}>"

        # Test with Optional type annotation
        mock_column.nullable = False
        mock_column.type.python_type = Optional[str]
        result = sqlalchemy_to_rust_type(sqlalchemy_type, mock_column)
        assert result == f"Option<{expected_rust_type}>"


class TestSQLAlchemyModelConversion:
    """Test cases for SQLAlchemy model conversion to Rust."""

    def test_get_required_imports(self, test_rust_model):
        """Test getting required imports for a model.

        Args:
            test_rust_model: Fixture providing the TestRustModel class
        """
        with patch(
            "nomy_data_models.py_to_rust.get_required_imports", return_value=set()
        ):
            # Call the original function to get the actual imports
            imports = get_required_imports(test_rust_model)

            # Verify that the required imports are included
            assert isinstance(imports, set), "Result should be a set"
            assert any(
                "use chrono" in imp for imp in imports
            ), "Should include chrono import"
            assert any(
                "use uuid::Uuid" in imp for imp in imports
            ), "Should include UUID import"
            assert any(
                "use serde_json::Value" in imp for imp in imports
            ), "Should include JSON import"
            assert any(
                "use rust_decimal::Decimal" in imp for imp in imports
            ), "Should include Decimal import"

    def test_get_required_imports_with_no_table(self):
        """Test getting required imports for a model without a __table__ attribute."""

        class ModelWithoutTable:
            pass

        imports = get_required_imports(ModelWithoutTable)
        assert isinstance(imports, set), "Result should be a set"
        assert (
            len(imports) == 0
        ), "Should return empty set for model without __table__ attribute"

    def test_get_required_imports_with_enum_column(self):
        """Test getting required imports for a model with an enum column."""

        class TestEnum(str, Enum):
            A = "a"
            B = "b"

        class ModelWithEnum(BaseModel):
            __abstract__ = False

            id = mapped_column(Integer, primary_key=True)
            enum_col = mapped_column(SQLAlchemyEnum(TestEnum), nullable=False)

        imports = get_required_imports(ModelWithEnum)
        assert "use crate::models::TestEnum;" in imports
        assert "use chrono::{DateTime, Utc};" in imports
        assert "use uuid::Uuid;" not in imports
        assert "use rust_decimal::Decimal;" not in imports

    def test_get_required_imports_with_enum_column_no_enum_class(self):
        """Test getting required imports for a model with an enum column that has no enum_class attribute."""

        class ModelWithEnumNoEnumClass(BaseModel):
            __abstract__ = False
            __table_args__ = {"extend_existing": True}

            id = mapped_column(Integer, primary_key=True)
            # Create a mock column with a type that has no enum_class attribute
            enum_col = mapped_column(Integer, nullable=False)
            created_at = mapped_column(DateTime, nullable=False)

        # Mock the columns
        id_column_mock = MagicMock()
        id_column_mock.name = "id"
        id_column_mock.type.__class__.__name__ = "Integer"

        # Mock a DateTime column
        datetime_column_mock = MagicMock()
        datetime_column_mock.name = "created_at"
        datetime_column_mock.type.__class__.__name__ = "DateTime"

        # Mock the column type to be "Enum" but without enum_class attribute
        enum_column_mock = MagicMock()
        enum_column_mock.name = "enum_col"
        enum_column_mock.type.__class__.__name__ = "Enum"
        # Ensure accessing enum_class raises AttributeError
        type(enum_column_mock.type).enum_class = PropertyMock(
            side_effect=AttributeError("No enum_class")
        )

        # Replace the columns with our mocks
        with patch.object(
            ModelWithEnumNoEnumClass.__table__,
            "columns",
            [id_column_mock, datetime_column_mock, enum_column_mock],
        ):
            imports = get_required_imports(ModelWithEnumNoEnumClass)

            # Verify that no enum import was added
            assert not any("use crate::models::" in imp for imp in imports)
            # DateTime import should be there
            assert "use chrono::{DateTime, Utc};" in imports

    def test_generate_rust_model(self, test_rust_model):
        """Test generating Rust model from SQLAlchemy model.

        Args:
            test_rust_model: Fixture providing the TestRustModel class
        """
        # Generate the Rust model
        result = generate_rust_model(test_rust_model)

        # Check that the model was generated correctly
        assert "pub struct RustModelExample {" in result
        assert "pub id: Uuid," in result
        assert "pub name: String," in result
        assert "pub age: i32," in result
        assert "pub is_active: bool," in result
        assert "pub created_at: DateTime<Utc>," in result
        assert "pub model_id: Uuid," in result
        assert "pub data: Option<JsonValue>," in result
        assert "pub amount: Option<f64>," in result
        assert "pub decimal_value: Option<Decimal>," in result
        assert "pub date_value: Option<NaiveDate>," in result
        assert "pub time_value: Option<NaiveTime>," in result
        assert "pub interval_value: Option<chrono::Duration>," in result
        assert "pub updated_at: DateTime<Utc>," in result
        assert "pub created_by: Option<String>," in result
        assert "pub updated_by: Option<String>," in result

        # Check that the constructor is generated correctly
        assert "impl RustModelExample {" in result
        assert "pub fn new(" in result
        assert "name: String," in result
        assert "age: i32," in result
        assert "is_active: bool," in result
        assert "created_at: DateTime<Utc>," in result
        assert "model_id: Uuid," in result
        assert "data: JsonValue," in result
        assert "amount: f64," in result
        assert "decimal_value: Decimal," in result
        assert "date_value: NaiveDate," in result
        assert "time_value: NaiveTime," in result
        assert "interval_value: chrono::Duration," in result
        assert "id: Uuid," in result
        assert "updated_at: DateTime<Utc>," in result
        assert "created_by: String," in result
        assert "updated_by: String," in result
        assert ") -> Self {" in result
        assert "Self {" in result

    def test_generate_rust_model_abstract_class(self):
        """Test generating Rust model from an abstract SQLAlchemy model."""
        # Should return empty string for abstract classes
        result = generate_rust_model(AbstractModel)
        assert result == "", "Should return empty string for abstract classes"

    def test_generate_rust_model_without_table(self):
        """Test generating Rust model from a model without a __table__ attribute."""

        class ModelWithoutTable:
            __name__ = "ModelWithoutTable"

        result = generate_rust_model(ModelWithoutTable)
        assert (
            result == ""
        ), "Should return empty string for models without __table__ attribute"

    def test_generate_rust_model_with_imports(self, test_rust_model):
        """Test generating Rust model with imports."""
        # Mock the template reading
        template_content = """
        // Model template
        {imports}

        /// {model_doc}
        #[derive(Debug, Clone, Serialize, Deserialize)]
        pub struct {model_name} {
        {fields}
        }

        impl {model_name} {
            pub fn new({constructor_args}) -> Self {
                Self {
        {constructor_body}
                }
            }
        }
        """

        # Create a set of imports
        imports = {
            "use chrono::{DateTime, Utc};",
            "use uuid::Uuid;",
            "use serde_json::Value as JsonValue;",
            "use rust_decimal::Decimal;",
            "use custom::Type;",  # Custom import that's not in the standard list
        }

        with patch("builtins.open", mock_open(read_data=template_content)):
            with patch("pathlib.Path.open", mock_open(read_data=template_content)):
                with patch(
                    "nomy_data_models.py_to_rust.get_required_imports",
                    return_value=imports,
                ):
                    # Call the function
                    result = generate_rust_model(test_rust_model)

                    # Verify the result contains the custom import
                    assert "use custom::Type;" in result, "Should include custom import"

    def test_generate_rust_models(self):
        """Test generating Rust models from all SQLAlchemy models."""
        # Create a temporary directory for output
        with tempfile.TemporaryDirectory() as temp_dir:
            # Mock get_all_models to return our test model
            with patch(
                "nomy_data_models.py_to_rust.get_all_models",
                return_value={"TestRustModel": RustModelExample},
            ):
                # Mock the enums
                with patch(
                    "nomy_data_models.py_to_rust.generate_rust_model",
                    return_value="// Mock Rust model",
                ):
                    with patch(
                        "nomy_data_models.py_to_rust.generate_rust_enum",
                        return_value="// Mock Rust enum",
                    ):
                        # Mock the directory operations
                        with patch("os.makedirs"):
                            # Mock file operations
                            with patch("builtins.open", mock_open()):
                                # Call the function
                                generate_rust_models(temp_dir)

                                # Since we've mocked everything, we can only verify that the function runs without errors
                                assert True, "Function should run without errors"

    def test_generate_rust_models_with_default_output_dir(self):
        """Test generating Rust models with default output directory."""
        # Mock get_all_models to return our test model
        with patch(
            "nomy_data_models.py_to_rust.get_all_models",
            return_value={"TestRustModel": RustModelExample},
        ):
            # Mock the enums
            with patch(
                "nomy_data_models.py_to_rust.generate_rust_model",
                return_value="// Mock Rust model",
            ):
                with patch(
                    "nomy_data_models.py_to_rust.generate_rust_enum",
                    return_value="// Mock Rust enum",
                ):
                    # Mock the directory operations
                    with patch("os.makedirs"):
                        # Mock file operations
                        with patch("builtins.open", mock_open()):
                            # Call the function with default output_dir
                            generate_rust_models()

                            # Since we've mocked everything, we can only verify that the function runs without errors
                            assert (
                                True
                            ), "Function should run without errors with default output_dir"

    def test_generate_rust_models_with_empty_model_output(self):
        """Test generating Rust models when generate_rust_model returns empty string."""
        # Create a temporary directory for output
        with tempfile.TemporaryDirectory() as temp_dir:
            # Mock get_all_models to return our test model
            with patch(
                "nomy_data_models.py_to_rust.get_all_models",
                return_value={"AbstractModel": AbstractModel},
            ):
                # Mock the enums to be empty
                with patch(
                    "nomy_data_models.py_to_rust.generate_rust_model", return_value=""
                ):
                    with patch(
                        "nomy_data_models.py_to_rust.generate_rust_enum",
                        return_value="// Mock Rust enum",
                    ):
                        # Mock the directory operations
                        with patch("os.makedirs"):
                            # Mock file operations
                            with patch("builtins.open", mock_open()):
                                # Call the function
                                generate_rust_models(temp_dir)

                                # Since we've mocked everything, we can only verify that the function runs without errors
                                assert (
                                    True
                                ), "Function should run without errors when generate_rust_model returns empty string"

    def test_get_all_models(self):
        """Test getting all SQLAlchemy models."""

        # Create a mock for BaseModel
        mock_base_model = MagicMock()
        mock_base_model.__name__ = "BaseModel"

        # Create a mock for a concrete model
        mock_concrete_model = MagicMock()
        mock_concrete_model.__name__ = "ConcreteModel"
        mock_concrete_model.__module__ = "nomy_data_models.models.concrete_model"
        mock_concrete_model.__mro__ = (mock_concrete_model, mock_base_model, object)

        # Create a mock for an abstract model
        mock_abstract_model = MagicMock()
        mock_abstract_model.__name__ = "AbstractModel"
        mock_abstract_model.__abstract__ = True
        mock_abstract_model.__module__ = "nomy_data_models.models.abstract_model"
        mock_abstract_model.__mro__ = (mock_abstract_model, mock_base_model, object)

        # Create a mock for a concrete model that inherits from an abstract model
        mock_concrete_abstract_model = MagicMock()
        mock_concrete_abstract_model.__name__ = "ConcreteAbstractModel"
        # Set __abstract__ = False to make it concrete
        mock_concrete_abstract_model.__abstract__ = False
        mock_concrete_abstract_model.__module__ = (
            "nomy_data_models.models.concrete_abstract_model"
        )
        mock_concrete_abstract_model.__mro__ = (
            mock_concrete_abstract_model,
            mock_abstract_model,
            mock_base_model,
            object,
        )

        # Create a mock for a model with __table_args__
        mock_model_with_table_args = MagicMock()
        mock_model_with_table_args.__name__ = "ModelWithTableArgs"
        mock_model_with_table_args.__table_args__ = {"sqlite_autoincrement": True}
        mock_model_with_table_args.__module__ = (
            "nomy_data_models.models.model_with_table_args"
        )
        mock_model_with_table_args.__mro__ = (
            mock_model_with_table_args,
            mock_base_model,
            object,
        )

        mock_external_model = MagicMock()
        mock_external_model.__name__ = "ExternalModel"
        mock_external_model.__module__ = "external_package.models"
        mock_external_model.__mro__ = (mock_external_model, mock_base_model, object)

        # Create a list of model names
        model_names = [
            "BaseModel",
            "ConcreteModel",
            "AbstractModel",
            "ConcreteAbstractModel",
            "ModelWithTableArgs",
            "ExternalModel",
        ]

        # Create a function to simulate the behavior of get_all_models
        def simulate_get_all_models():
            result = {}
            for name in model_names:
                if name == "BaseModel":
                    item = mock_base_model
                elif name == "ConcreteModel":
                    item = mock_concrete_model
                elif name == "AbstractModel":
                    item = mock_abstract_model
                elif name == "ConcreteAbstractModel":
                    item = mock_concrete_abstract_model
                elif name == "ModelWithTableArgs":
                    item = mock_model_with_table_args
                elif name == "ExternalModel":
                    item = mock_external_model
                else:
                    continue

                if hasattr(item, "__mro__") and mock_base_model in item.__mro__:
                    # The golden rule: A class is concrete if __abstract__ is False or not defined
                    is_abstract = getattr(item, "__abstract__", False)
                    if (
                        item != mock_base_model
                        and not is_abstract
                        and item.__module__.startswith("nomy_data_models.models")
                    ):
                        result[name] = item
            return result

        # Call the function
        result = simulate_get_all_models()

        # Verify the result
        assert isinstance(result, dict), "Result should be a dictionary"
        assert "ConcreteModel" in result, "Should include concrete models"
        assert (
            "ConcreteAbstractModel" in result
        ), "Should include concrete models that inherit from abstract models"
        assert (
            "ModelWithTableArgs" in result
        ), "Should include models with __table_args__"
        assert (
            "AbstractModel" not in result
        ), "Should not include abstract models without table attributes"
        assert "BaseModel" not in result, "Should not include BaseModel"

    def test_get_all_models_with_real_models(self):
        """Test getting all SQLAlchemy models with real models from the package."""
        # This test will use the actual models from the package
        # It's more of an integration test than a unit test

        # Call the function
        result = get_all_models()

        # Verify the result
        assert isinstance(result, dict), "Result should be a dictionary"
        assert len(result) > 0, "Should find at least one model"

        # Check that BaseModel is not included
        from nomy_data_models.models.base import BaseModel

        assert "BaseModel" not in result, "Should not include BaseModel"

        # Check that all models in the result are SQLAlchemy models
        for name, model in result.items():
            assert issubclass(
                model, BaseModel
            ), f"Model {name} should be a SQLAlchemy model"
            assert model.__module__.startswith(
                "nomy_data_models.models"
            ), f"Model {name} should be from nomy_data_models.models package"

    def test_generate_rust_model_with_unknown_type(self):
        """Test generating Rust model with an unknown SQLAlchemy type."""
        # Create a mock model with an unknown column type
        mock_model = MagicMock()
        mock_model.__name__ = "MockModel"
        mock_model.__doc__ = "A mock model with an unknown column type."
        mock_model.__abstract__ = False

        # Create a mock column with an unknown type
        mock_column = MagicMock()
        mock_column.name = "unknown_column"
        mock_column.type = MagicMock()
        type(mock_column.type).__name__ = "UnknownType"
        mock_column.nullable = False

        # Create a mock table with the column
        mock_table = MagicMock()
        mock_table.columns = [mock_column]

        # Assign the mock table to the model
        mock_model.__table__ = mock_table

        # Capture stdout to check for the warning message
        import io
        import sys

        captured_output = io.StringIO()
        sys.stdout = captured_output

        try:
            # Generate the Rust model
            result = generate_rust_model(mock_model)

            # Check that the warning message was printed
            warning_message = captured_output.getvalue()
            assert "Warning: Unknown SQLAlchemy type UnknownType" in warning_message
            assert "defaulting to String" in warning_message

            # Check that the model was generated with the unknown column as String
            assert "pub unknown_column: String," in result
        finally:
            sys.stdout = sys.__stdout__

    def test_print_unknown_type_warning(self):
        """Test the _print_unknown_type_warning function."""
        # Capture stdout to check for the warning message
        import io
        import sys

        captured_output = io.StringIO()
        sys.stdout = captured_output

        try:
            # Call the function with a test type
            _print_unknown_type_warning("TestType")

            # Check that the warning message was printed
            warning_message = captured_output.getvalue()
            assert "Warning: Unknown SQLAlchemy type TestType" in warning_message
            assert "defaulting to String" in warning_message
        finally:
            # Reset stdout
            sys.stdout = sys.__stdout__

    def test_generate_rust_model_fields(self):
        """Test the field generation in the generate_rust_model function."""
        # Create a mock model with a simple column
        mock_model = MagicMock()
        mock_model.__name__ = "MockModel"
        mock_model.__doc__ = "A mock model for testing field generation."
        mock_model.__abstract__ = False

        # Create a mock column with a known type
        mock_column = MagicMock()
        mock_column.name = "test_field"
        mock_column.type = MagicMock()
        type(mock_column.type).__name__ = "String"
        # Explicitly set nullable to False
        mock_column.nullable = False
        mock_column.type.python_type = str

        # Create a mock table with the column
        mock_table = MagicMock()
        mock_table.columns = [mock_column]

        # Assign the mock table to the model
        mock_model.__table__ = mock_table

        # Generate the Rust model
        result = generate_rust_model(mock_model)

        # Check that the field was generated correctly
        assert "pub test_field: String," in result

    def test_generate_rust_model_multiple_fields(self):
        """Test generating Rust model with multiple fields to ensure field generation loop is covered."""
        # Create a mock model with multiple columns
        mock_model = MagicMock()
        mock_model.__name__ = "MultiFieldModel"
        mock_model.__doc__ = "A mock model with multiple fields for testing."
        mock_model.__abstract__ = False

        # Create mock columns with different types
        columns = []
        for i, type_name in enumerate(
            ["String", "Integer", "Boolean", "DateTime", "UUID"]
        ):
            mock_column = MagicMock()
            mock_column.name = f"field_{i}"
            mock_column.type = MagicMock()
            type(mock_column.type).__name__ = type_name
            mock_column.nullable = False
            mock_column.type.python_type = str
            columns.append(mock_column)

        # Create a mock table with the columns
        mock_table = MagicMock()
        mock_table.columns = columns

        # Assign the mock table to the model
        mock_model.__table__ = mock_table

        # Generate the Rust model
        result = generate_rust_model(mock_model)

        # Check that all fields were generated correctly
        assert "pub field_0: String," in result
        assert "pub field_1: i32," in result
        assert "pub field_2: bool," in result
        assert "pub field_3: DateTime<Utc>," in result
        assert "pub field_4: Uuid," in result

    def test_generate_rust_fields_function(self):
        """Test the _generate_rust_fields function directly."""
        # Create test columns
        columns = [
            ("id", "Uuid"),
            ("name", "String"),
            ("age", "i32"),
            ("is_active", "bool"),
            ("created_at", "DateTime<Utc>"),
        ]

        # Call the function
        fields = _generate_rust_fields(columns)

        # Verify the results
        assert len(fields) == 5, "Should generate 5 field definitions"
        assert "    pub id: Uuid," in fields
        assert "    pub name: String," in fields
        assert "    pub age: i32," in fields
        assert "    pub is_active: bool," in fields
        assert "    pub created_at: DateTime<Utc>," in fields

    def test_generate_rust_model_with_none_type(self):
        """Test generating Rust model when sqlalchemy_to_rust_type returns None."""
        # Create a mock model
        mock_model = MagicMock()
        mock_model.__name__ = "MockModelWithNoneType"
        mock_model.__doc__ = "A mock model for testing None type handling."
        mock_model.__abstract__ = False

        # Create a mock column with a type that will return None
        mock_column = MagicMock()
        mock_column.name = "none_type_field"
        mock_column.type = MagicMock()
        type(mock_column.type).__name__ = "NoneType"

        # Create a mock table with the column
        mock_table = MagicMock()
        mock_table.columns = [mock_column]

        # Assign the mock table to the model
        mock_model.__table__ = mock_table

        # Mock sqlalchemy_to_rust_type to return None for NoneType
        with patch(
            "nomy_data_models.py_to_rust.sqlalchemy_to_rust_type",
            side_effect=lambda t, c=None: None if t == "NoneType" else "String",
        ):
            # Capture stdout to check for the warning message
            import io
            import sys

            captured_output = io.StringIO()
            sys.stdout = captured_output

            try:
                # Generate the Rust model
                result = generate_rust_model(mock_model)

                # Check that the warning message was printed
                warning_message = captured_output.getvalue()
                assert "Warning: Unknown SQLAlchemy type NoneType" in warning_message
                assert "defaulting to String" in warning_message

                # Check that the model was generated with the field as String
                assert "pub none_type_field: String," in result
            finally:
                # Reset stdout
                sys.stdout = sys.__stdout__

    def test_generate_rust_model_with_multiline_docstring(self):
        """Test generating a Rust model with a multi-line docstring."""

        class ModelWithMultilineDoc(BaseModel):
            """This is a model with a multi-line docstring.

            It has multiple lines.
            And even more lines.
            """

            __abstract__ = False

            id = mapped_column(Integer, primary_key=True)
            name = mapped_column(String(50), nullable=False)

        result = generate_rust_model(ModelWithMultilineDoc)

        assert "/// This is a model with a multi-line docstring." in result
        assert "It has multiple lines." in result
        assert "And even more lines." in result

    def test_generate_rust_model_with_annotations(self):
        """Test generating a Rust model using __annotations__ instead of __table__."""

        class ModelWithAnnotations:
            """Model with annotations."""

            __name__ = "ModelWithAnnotations"

            id: int
            name: str
            is_active: bool
            created_at: "datetime"
            model_id: "UUID"
            amount: float
            decimal_value: "Decimal"
            data: dict

        result = generate_rust_model(ModelWithAnnotations)

        assert "pub struct ModelWithAnnotations {" in result
        assert "pub id: i32," in result
        assert "pub name: String," in result
        assert "pub is_active: bool," in result
        assert "pub created_at: DateTime<Utc>," in result
        assert "pub model_id: Uuid," in result
        assert "pub amount: f64," in result
        assert "pub decimal_value: Decimal," in result
        assert "pub data: JsonValue," in result

    def test_generate_rust_models_file_writing(self, tmp_path):
        """Test that generate_rust_models writes files correctly and generates mod.rs content."""
        # This test is simplified to just verify that the function runs without errors
        # and that the appropriate mocks are called

        # Mock get_all_models to return a dictionary
        with patch(
            "nomy_data_models.py_to_rust.get_all_models",
            return_value={"TestModel1": MagicMock(), "TestModel2": MagicMock()},
        ):
            # Mock generate_rust_model to return a non-empty string
            with patch(
                "nomy_data_models.py_to_rust.generate_rust_model",
                return_value="// Mock Rust model",
            ):
                # Mock generate_rust_enum to return a non-empty string
                with patch(
                    "nomy_data_models.py_to_rust.generate_rust_enum",
                    return_value="// Mock Rust enum",
                ):
                    # Mock Path.mkdir to avoid creating directories
                    with patch("pathlib.Path.mkdir"):
                        # Mock open to avoid file operations
                        with patch("builtins.open", mock_open()) as mock_file:
                            # Call the function
                            generate_rust_models(output_dir=str(tmp_path))

                            # Verify that open was called at least once
                            mock_file.assert_called()

                            # Verify that write was called at least once
                            mock_file().write.assert_called()

    def test_get_all_models_with_external_module(self):
        """Test getting all SQLAlchemy models with a class from an external module."""
        from nomy_data_models.models.base import BaseModel

        # Create a mock class that inherits from BaseModel but is in a different module
        class ExternalModel(BaseModel):
            __module__ = "external_package.models"
            __abstract__ = False

        # Patch dir to return our external model
        with patch("nomy_data_models.py_to_rust.dir", return_value=["ExternalModel"]):
            # Patch getattr to return our external model when asked for ExternalModel
            with patch(
                "nomy_data_models.py_to_rust.getattr",
                side_effect=lambda module, name: (
                    ExternalModel if name == "ExternalModel" else getattr(module, name)
                ),
            ):
                # Call the function
                result = get_all_models()

                # Verify the result
                assert isinstance(result, dict), "Result should be a dictionary"
                assert (
                    "ExternalModel" not in result
                ), "Should not include models from external packages"

    def test_generate_rust_model_without_table_or_annotations(self):
        """Test generating Rust model from a model without __table__ or __annotations__."""
        # Create a mock model without __table__ or __annotations__
        mock_model = MagicMock(spec=["__name__", "__doc__", "__abstract__"])
        mock_model.__name__ = "MockModelWithoutAttributes"
        mock_model.__doc__ = "A mock model without __table__ or __annotations__."
        mock_model.__abstract__ = False

        # Generate the Rust model
        result = generate_rust_model(mock_model)

        # Check that it returns an empty string
        assert (
            result == ""
        ), "Should return empty string for models without __table__ or __annotations__"

    def test_generate_rust_model_with_optional_and_union_types(self):
        """Test generating a Rust model with Optional and Union type annotations."""
        from typing import Optional, Union

        class ModelWithOptionalAndUnion:
            """Model with Optional and Union type annotations."""

            __name__ = "ModelWithOptionalAndUnion"
            __annotations__ = {
                "id": int,
                "name": Optional[str],
                "age": Union[int, None],
                "data": Optional[dict],
            }

        result = generate_rust_model(ModelWithOptionalAndUnion)

        assert "pub struct ModelWithOptionalAndUnion {" in result
        assert "pub id: i32," in result
        assert "pub name: Option<String>," in result
        assert "pub age: Option<i32>," in result
        assert "pub data: Option<JsonValue>," in result


if __name__ == "__main__":
    pytest.main(["-v", __file__])